package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.dao.UserListDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserListService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
@Service
public class UserLiserviceImpl implements UserListService {

    @Autowired
    UserListDao userListDao;

    @Autowired
    RoleDao roleDao;


    @Override
    public void add(User user, Integer[] roleIds) {
        userListDao.insert(user);

        for (Integer roleId : roleIds) {
            userListDao.insertRoleByUserId(user.getId(),roleId);
        }
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //使用分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        // 分页查询数据库
        Page<User> page = userListDao.selectByConditon(queryPageBean.getQueryString());
        //封装分页数据
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void delete(int id) {
        long l = userListDao.countdeleteByUserId(id);
        if(l>0){
            throw new BusinessRuntimeException("数据有关联 不能删除");
        }
        userListDao.deleteById(id);
    }

    @Override
    public void edit(User user,Integer[] roleIds) {
        userListDao.update(user);

        userListDao.deleteRoleIdbyUserId(user.getId());

        for (Integer roleId : roleIds) {
            userListDao.insertRoleIdsByUserId(user.getId(),roleId);
        }
    }

    @Override
    public User findById(Integer id) {
        User user = userListDao.selectById(id);
        return user;
    }

    @Override
    public List<Role> findAll() {
        return roleDao.selectAll();
    }

    @Override
    public List<Integer> findRoleIdsByUserIds(Integer id) {
        return userListDao.selectRoleIdsByUserId(id);
    }


}
